package com.sanery.ui.controller;

import java.io.File;
import java.io.IOException;
import java.util.Date;
import java.util.List;
import java.util.UUID;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpSession;

import org.springframework.format.annotation.DateTimeFormat;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.multipart.MultipartFile;

import com.sanery.entity.Discovery;
import com.sanery.entity.User;
import com.sanery.service.DiscoveryService;
import com.sanery.service.impl.DiscoveryServiceImpl;

@Controller
public class DiscoveryController {
	DiscoveryService service = new DiscoveryServiceImpl();

	@RequestMapping(value = "/index", method = RequestMethod.GET)
	public String index(Model m) {
		List<Discovery> list = service.getAll();
		m.addAttribute("list", list);
		return "/index";
	}

	@RequestMapping(value = "/list", method = RequestMethod.GET)
	public String list(Model m, HttpSession session) {
		User user = (User) session.getAttribute("user");
		Integer id = user.getId();
		List<Discovery> list = service.getMy(id);
		m.addAttribute("list", list);
		return "/list";
	}

	@RequestMapping(value = "/add", method = RequestMethod.GET)
	public String add() {
		return "/add";
	}

	@RequestMapping(value = "/add", method = RequestMethod.POST)
	public String add(Discovery discovery, MultipartFile photo, HttpServletRequest request)
			throws IllegalStateException, IOException {
		String prjdir = request.getServletContext().getRealPath("/");
		String imgdir = new File(prjdir).getParent() + "/imagesdir";// webapps/images_discover-图片上传到这个位置

		File imgdirFile = new File(imgdir);
		if (imgdirFile.exists() == false)
			imgdirFile.mkdirs();// 如果目录不存在，我们可以自动创建这个目录

		if (photo.isEmpty() == false) {// 上传来的文件是否是空的
			// 制造文件名（先要提取后缀)
			String ext = photo.getOriginalFilename().substring(photo.getOriginalFilename().lastIndexOf("."));
			String imgname = UUID.randomUUID().toString() + ext;
			// 拷贝到目标目录(webapps/imagesdir/)
			photo.transferTo(new File(imgdir + "/" + imgname));// 保存到指定位置

			discovery.setImgname(imgname);// 填进压缩包，准备保存到数据库
		}

		User u = (User) request.getSession().getAttribute("user");
		discovery.setUserid(u.getId());

		service.add(discovery);
		return "redirect:/index";
	}

	@RequestMapping(value = "/del")
	public String del(Integer id) {
		service.delDiscovery(id);
		return "redirect:/index";
	}

	@RequestMapping(value = "/sel")
	public String sel(@DateTimeFormat(pattern = "yyyy-MM-dd") Date begintime,
			@DateTimeFormat(pattern = "yyyy-MM-dd") Date endtime, Model m, HttpSession session) {
		User user = (User) session.getAttribute("user");
		Integer id = user.getId();
		List<Discovery> list = service.getSel(begintime, endtime, id);
		m.addAttribute("list", list);
		return "/list";
	}
}
